import ImageCompressor from "image-compressor.js"
import { ref } from "vue"
const img = ref(null)
export function base64ToFile(base64String: any, filename: any) {

    // 将base64字符串转换为Blob对象
    const byteCharacters = atob(base64String.split(';base64,').pop());
    const byteNumbers = new Array(byteCharacters.length);
    for (let i = 0; i < byteCharacters.length; i++) {
        byteNumbers[i] = byteCharacters.charCodeAt(i);
    }
    const byteArray = new Uint8Array(byteNumbers);
    const blob = new Blob([byteArray], { type: 'image/png' });

    return new File([blob], filename, { type: 'image/png' });
}
export function compressImage(file: any) {
    try {
        const reader = new FileReader();

        file = base64ToFile(file.value, 'newImage');
        new ImageCompressor(file, {
            maxWidth: 800,
            maxHeight: 800,
            quality: 0.6,
            mimeType: "image/png",
            success(result:any) {
                reader.onload = function (event) {
                    img.value = event.target.result.toString();
                };

                reader.onerror = function (error) {
                    console.error('FileReader error:', error);
                    // 在出错时返回错误信息
                    throw error;
                };

                reader.readAsDataURL(result);
            },
            error(e) {
                console.error( e.message);
                throw e.message;
            },
        });

    } catch (error) {
        console.error(error);
        throw error;
    }
    return img;
}
